package es.tikitaka.actions;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;

import es.tikitaka.dictionary.ProvinciaDic;
import es.tikitaka.domain.usuarios.Usuario;

/**
 * 
 * @author Saúl Domínguez
 * @since 2010
 * @category PFC
 */

@Name("autenticador")
@Scope(ScopeType.SESSION)
public class Autenticador implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7268876006597745970L;

	@Logger
	private Log log;

	@In
	private EntityManager em;

	@Out(required = false)
	Usuario user;

	@Out(required = false)
	ProvinciaDic provinciaUsuario;

	private Boolean login;

	@SuppressWarnings("unchecked")
	public boolean autenticar() {

		List results = em
				.createQuery(
						"select u from Usuario u where u.username=#{identity.username} and u.password=#{identity.password}")
				.getResultList();

		if (results.size() == 0) {
			return false;
		} else {
			user = (Usuario) results.get(0);
			return true;
		}

	}

	public Boolean getLogin() {
		return login;
	}

	public void setLogin(Boolean login) {
		this.login = login;
	}

	@Observer("org.jboss.seam.security.alreadyLoggedIn")
	@Begin(join = true)
	public void alreadyLoggedIn() {
		log.info("Ya estas conectado");
	}

	public Usuario getUser() {
		return user;
	}

	public void setUser(Usuario user) {
		this.user = user;
	}

}